# coding:utf-8

import numpy as np
import cv2

# opencv读取图片
def alpha2white_opencv2(img):
    sp = img.shape
    # 无alpha通道
    if sp[2] <= 3:
        return img

    # 有alpha通道(比如有透明背景的png图片)
    width = sp[0]
    height = sp[1]
    for yh in range(height):
        for xw in range(width):
            color_d = img[xw, yh]
            if color_d[3] != 255:  # 找到alpha通道不為255的像素
                img[xw, yh] = [255, 255, 255, 255]  # 改變這個像素
    return img


def save_img_to_txt(image_path, txt_path):
    img = cv2.imdecode(
        np.fromfile(image_path, dtype=np.uint8), cv2.IMREAD_UNCHANGED
    )  # 第二个参数 保留Alpha 通道
    # img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)  # 第二个参数 保留Alpha 通道
    # print(img.shape)
    img = alpha2white_opencv2(img)

    # 图像灰度化(降低图片像素大小)
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # 直接阈值化是对输入的单通道矩阵逐像素进行阈值分割(效果较差!!!)
    ret, binary_img = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

    # 打开窗口显示图像
    cv2.namedWindow("origin", 0)
    cv2.resizeWindow("origin", 800, 600)
    cv2.imshow("origin", binary_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # 保存为txt数据文件
    binary_img = np.where(binary_img < 1, binary_img, 1)  # 小于1的不变，其他更换为1
    np.savetxt(txt_path, binary_img, fmt="%d")


# 图片路径
image_path = "./pixil-frame-0.png"
# image_path = "./New Piskel.jpg"
# image_path = "./微信图片_20200905205339.png"
# 经灰度化、二值化处理后, 将黑白图片(0-黑, 255-白)转换为(0-黑 1-白)矩阵,并保存到txt文件
save_img_to_txt(image_path, "./data.txt")
